package yiran.stock;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.stock.command.BuyCommand;
import yiran.stock.gui.StockGUI;
import yiran.stock.lang.LangHelper;
import yiran.stock.manager.StockPriceUpdateEvent;

import java.util.ArrayList;

public class GuiManager implements Listener {
    private final Stock plugin;

    public GuiManager(Stock plugin) {
        this.plugin = plugin;
    }

    public static void register(JavaPlugin plugin) {
        Bukkit.getPluginManager().registerEvents(new GuiManager((Stock) plugin), plugin);
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        String title = event.getView().getTitle();
        Player player = (Player) event.getWhoClicked();

        if (title.startsWith(LangHelper.getString("gui.buy-title-prefix"))) {
            event.setCancelled(true);
            ItemStack clicked = event.getCurrentItem();
            if (clicked == null || clicked.getType() != Material.PAPER) return;

            String symbol = plugin.getBuyManager().getPlayerSelection(player);
            if (symbol == null) return;

            String displayName = clicked.getItemMeta().getDisplayName();
            int quantity = Integer.parseInt(displayName.replace(ChatColor.YELLOW + "", "").replace(" 股", ""));

            BuyCommand.processBuyTransaction(
                    player,
                    plugin.getStockManager(),
                    player,
                    symbol,
                    quantity,
                    plugin.getEconomy()
            );

            player.closeInventory();
            plugin.getBuyManager().clearSelection(player);
            return;
        }

        if (!title.startsWith(LangHelper.getString("gui.title"))) return;

        event.setCancelled(true);
        if (!(event.getWhoClicked() instanceof Player)) return;

        StockGUI gui = StockCommand.openGUIs.get(player.getUniqueId());
        if (gui != null) gui.handleClick(event.getRawSlot());
    }

    @EventHandler
    public void onInventoryClose(InventoryCloseEvent event) {
        String title = event.getView().getTitle();
        if (!title.startsWith(LangHelper.getString("gui.title"))) return;

        if (event.getPlayer() instanceof Player) {
            StockCommand.openGUIs.remove(event.getPlayer().getUniqueId());
        }
    }

    @EventHandler
    public void onStockPriceUpdate(StockPriceUpdateEvent event) {
        new ArrayList<>(StockCommand.openGUIs.values()).forEach(gui -> {
            if (gui.player.isOnline()) {
                gui.refreshCurrentPage();
            }
        });
    }
}
